package com.sicaolong.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.sicaolong.io.Resource;
import com.sicaolong.pojo.Configuration;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author : sicaolong
 * @description :
 * @date : 2020/10/15  11:56 下午
 */
public class XMLConfigBuilder {

	private Configuration configuration;

	public XMLConfigBuilder() {
		this.configuration = new Configuration();
	}

	/**
	 * 该方法就是使用dom4j配置文件进行解析 封装Configuration的方法
	 *
	 * @param inputStream
	 * @return
	 */
	public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

		Document document = new SAXReader().read(inputStream);
		Element rootElement = document.getRootElement();
		List<Element> list = rootElement.selectNodes("//properties");
		Properties properties = new Properties();
		for (Element element : list) {
			String name = element.attributeValue("name");
			String value = element.attributeValue("value");
			properties.setProperty(name, value);
		}
		ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
		comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
		comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
		comboPooledDataSource.setUser(properties.getProperty("username"));
		comboPooledDataSource.setPassword(properties.getProperty("password"));
		configuration.setDataSource(comboPooledDataSource);

		//mapper.xml 配置解析
		List<Element> list1 = rootElement.selectNodes("//mapper");
		for (Element element : list1) {
			String mapperPath = element.attributeValue("resource");
			InputStream resourceAsStream = Resource.getResourceAsStream(mapperPath);
			XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
			xmlMapperBuilder.parse(resourceAsStream);
		}
		return configuration;
	}
}